import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Button, Card, Flex, message } from 'ant-design-vue';

interface User {
  id: string // 添加唯一ID
  name: string
  age: number
  email: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const users = ref<User[]>([
    { id:'1',name: 'zhangsan', age: 18,email: '111111@qq.com' },
    { id:'2',name: 'lisi', age: 10,email: '111111@qq.com' },
    { id:'3',name: 'wangliu', age: 20,email: '111111@qq.com' }
  ])
  const userId = ref<String | null>(null)
 // 当前编辑的用户
  // const editUserId = ref<User | null>(null)
  // Getter（计算属性）
  // 成年
  const adultUsers = computed(() => {
    return users.value.filter(user => user.age >= 18)
  })
// underUsers 未成年
 const underUsers = computed(() => {
    return users.value.filter(user => user.age < 18)
  })
  // Action（修改方法）
  const incrementAge = (index: number) => {
    users.value[index].age += 1
  }
    const editUserId = (id: String) => {
    userId.value = id
  }
  const editUsers = (updatedUser:User)=>{
    // 编辑用户
    console.log('updatedUser',updatedUser);
    console.log('updatedUserId',userId.value);
    
 const index = users.value.findIndex(u => u.id === userId.value)
  if (index !== -1) {
      users.value.splice(index, 1, { ...updatedUser, id: userId.value })
    }
  }

 const addUser = (user: Omit<User, 'id'>) => {
    users.value.push({
      ...user,
      id: Date.now().toString() // 自动生成ID
    })
  }
  // 删除
  const deleteUser = (id: String) => {
   const index = users.value.findIndex(user => user.id === id);
  if (index !== -1) {
    users.value.splice(index, 1);
    message.success('删除成功');
  } else {
    message.error('未找到该用户');
  }
  }

  return {
    users,
    adultUsers,
    underUsers,
    incrementAge,
    addUser,
    editUsers,
    editUserId,
    userId,
    deleteUser
  }
})
